import { baseURL } from '@/api/_client.ts';
import { getTrainingCourse } from '@/api/agriculture.ts';
import { defineStore } from 'pinia';
import { computed, ref } from 'vue';

export const useCoursesStore = defineStore('CoursesStore', () => {
  const courseData = ref<any[]>([]);
  const loading = ref<boolean>(false);
  const coursePage = ref({
    currentPage: 1,
    total: 0,
    pageSize: 10,
    showSizePicker: true,
    pageSizes: Array.from({ length: 200 }, (_, index) => index + 1),
  });

  const updateCourseData = async (term?: string) => {
    loading.value = true;
    const req = {
      pageNo: coursePage.value.currentPage,
      pageSize: coursePage.value.pageSize,
      searchTerm: term || undefined,
    };
    if (term) {
      req.pageNo = 1;
    }
    const res = await getTrainingCourse(req);
    const { data, meta } = res;

    courseData.value = data.map((item: any) => ({
      id: item.id,
      title: item.attributes.title,
      image: baseURL + `${item.attributes.image.data.attributes.url}`,
      date: item.attributes.time,
      location: item.attributes.Area,
      instructor: item.attributes.description,
    }));
    coursePage.value.total = meta.pagination.total;
    if (term) {
      if (meta.pagination.total > 0) {
        ElMessage.success(`搜索'${term}'成功，共 ${meta.pagination.total} 条课程数据`);
      } else {
        ElMessage.warning(`暂无'${term}'课程数据`);
      }
    }
    loading.value = false;
  };

  // 设置分页信息
  const setCoursePage = (page?: number) => {
    if (page) coursePage.value.currentPage = page;
  };

  const getCourseData = computed(() => {
    return courseData.value;
  });

  const getCoursePage = computed(() => {
    return coursePage.value;
  });

  const pagination = computed(() => ({
    current: coursePage.value.currentPage,
    total: coursePage.value.total,
    pageSize: coursePage.value.pageSize,
    onChange: (page: number) => {
      setCoursePage(page);
      updateCourseData().then();
    },
  }));

  const getCourseLoading = computed(() => {
    return loading.value;
  });

  return {
    updateCourseData,
    getCourseData,
    coursePage,
    setCoursePage,
    getCoursePage,
    pagination,
    getCourseLoading,
  };
});
